﻿#include "tcpfileget.h"
#include <QDataStream>

tcpFileGet::tcpFileGet()
{
    m_listenPort = "10086";

    connect(&m_tcpServer,SIGNAL(newConnection()),
            this,SLOT(acceptConnection()));

}

void tcpFileGet::openlisten()
{   
    qDebug() << "tcp try to open port: " << m_listenPort.toInt();
    if(!m_tcpServer.listen(QHostAddress::LocalHost,m_listenPort.toInt()))
    {
        qDebug()<<m_tcpServer.errorString();

        emit sig_GetError(m_tcpServer.errorString());

        return;
    }

    m_totalBytes=0;
    m_bytesReceived=0;
    m_fileNameSize=0;

}

void tcpFileGet::closelisten()
{
    qDebug() << "tcp try to close port: " << m_listenPort.toInt();
    m_tcpServer.close();
}

void tcpFileGet::acceptConnection()
{
    m_tcpServerConnection=m_tcpServer.nextPendingConnection();
    connect(m_tcpServerConnection,SIGNAL(readyRead()),
            this,SLOT(updateServerProgress()));
    connect(m_tcpServerConnection,SIGNAL(error(QAbstractSocket::SocketError)),
            this,SLOT(displayError(QAbstractSocket::SocketError)));

    closelisten();
}

void tcpFileGet::updateServerProgress()
{
    QDataStream in(m_tcpServerConnection);
    in.setVersion(QDataStream::Qt_5_7);
    // 如果接收到的数据小于16个字节，保存到来的文件头结构
    if (m_bytesReceived<=(qint64)(sizeof(qint64)*2)){
        if((m_tcpServerConnection->bytesAvailable()>=(qint64)(sizeof(qint64)*2))&&(m_fileNameSize==0)){
            // 接收数据总大小信息和文件名大小信息
            in>>m_totalBytes>>m_fileNameSize;
            m_bytesReceived +=sizeof(qint64)*2;
        }
        if((m_tcpServerConnection->bytesAvailable()>=m_fileNameSize)&&(m_fileNameSize!=0)){
            // 接收文件名，并建立文件
            in>>m_fileName;
            m_bytesReceived+=m_fileNameSize;
            m_localFile = new QFile(m_fileName);
            if (!m_localFile->open(QFile::WriteOnly)){
                qDebug() << "server: open file error!";
                return;
            }
        }
        else{
            return;
        }
    }
    // 如果接收的数据小于总数据，那么写入文件
    if(m_bytesReceived<m_totalBytes) {
        m_bytesReceived+=m_tcpServerConnection->bytesAvailable();
        m_inBlock = m_tcpServerConnection->readAll();
        m_localFile->write(m_inBlock);
        m_inBlock.resize(0);
    }

    if(m_bytesReceived!=m_totalBytes)
    {
        emit sig_GetProgress(m_bytesReceived*100/m_totalBytes);
    }else{
        m_tcpServerConnection->close();
        m_localFile->close();
        emit sig_GetProgress(100);
        openlisten();

    }

}

void tcpFileGet::displayError(QAbstractSocket::SocketError socketError)
{
    Q_UNUSED(socketError)
    qDebug()<<m_tcpServerConnection->errorString();
    m_tcpServerConnection->close();
    emit sig_GetError(m_tcpServerConnection->errorString());

}

